﻿using LPLS.Commons.Enums;
using LPLS.DBEntities.OEEModule.OEEModels.DataStatisticModels;
using LPLS.DBInterface.OEEModule.OEEModels.DataStaticsticModels;
using OxyPlot;
using OxyPlot.Axes;
using OxyPlot.Legends;
using OxyPlot.Series;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataStatisticsChartModule.ViewModels
{


   public  class TubeDataStatisticsChartViewModel : BindableBase
    {
        private readonly ICompentDataStatisticsService _tubeDataStatisticsService;
        public TubeDataStatisticsChartViewModel(ICompentDataStatisticsService tubeDataStatisticsService  ) 
        {
            _tubeDataStatisticsService= tubeDataStatisticsService;
            DataStatisticsEvent.OnDataStatisticsEvent += DataStatisticsEvent_OnDataStatisticsEvent;
        }
        public DataStatisticsEventModel EventModel { get; set; }

        private void DataStatisticsEvent_OnDataStatisticsEvent(DataStatisticsEventModel obj)
        {
            EventModel = new DataStatisticsEventModel();
            EventModel = obj;
            var starttime = obj.StartTime;
            var endtime = obj.EndTime;
            var deviceid = obj.DeviceModel.ID;
            QueryData(starttime, endtime, deviceid);
        }
        private PlotModel _TubeDataPieChartModel;
        public PlotModel TubeDataPieChartModel
        {
            get { return _TubeDataPieChartModel; }
            set
            {
                SetProperty(ref _TubeDataPieChartModel, value);
            }
        }
        private PlotModel _TubeEveryAlarmByTimeModel;
        public PlotModel TubeEveryAlarmByTimeModel
        {
            get { return _TubeEveryAlarmByTimeModel; }
            set
            {
                SetProperty(ref _TubeEveryAlarmByTimeModel, value);
            }
        }
        private PlotModel _TubeDataLineBarChartModel;
        public PlotModel TubeDataLineBarChartModel
        {
            get { return _TubeDataLineBarChartModel; }
            set
            {
                SetProperty(ref _TubeDataLineBarChartModel, value);
            }
        }
        /// <summary>
        /// 数据查询方法
        /// </summary>
        private void QueryData(DateTime starttime, DateTime endtime, Guid  deviceid)
        {
            ///获取到了数据
            var data = _tubeDataStatisticsService.GetData(starttime, endtime, deviceid);
            #region  对数据进行筛选
            QueryTubeDataPieChartModelData(data);
            QueryTubeEveryAlarmByTimeToLineBar(data);
            QueryTubeDataLineBarChartModel(data);
            QuaryDeviceDataToDataGid(data);
            #endregion
        }
        /// <summary>
        /// 每种状态的时间总占比
        /// </summary>
        /// <param name="data"></param>
        private void QueryTubeDataPieChartModelData(List<CompentDataStatistics> data)
        {

            #region  TubeDataPieChartModel 赋值
            var tmp = new PlotModel { Title = "组件各状态占比统计", Subtitle = "单位(分钟)" };

            PieSeries series4 =
                new PieSeries {
                StrokeThickness = 1,
                InsideLabelPosition = 0.8,
                Diameter = 0.9
            };
            var groupedData = data.GroupBy(d => d.Status).Select(g => new { Status = g.Key, TotalTime = g.Sum(d => d.TotalSecondTime) / 60 }).ToList();

            Parallel.ForEach(groupedData, item =>
            {
                series4.Slices.Add(new PieSlice(item.Status.GetDescription(), item.TotalTime)
                {
                    IsExploded = true,

                });
            });
            Legend l = new Legend();
            l = GetLanguage();
            tmp.Legends.Add(l);
            tmp.Series.Add(series4);
            TubeDataPieChartModel = tmp;


            #endregion

        }
        private void QueryTubeEveryAlarmByTimeToLineBar(List<CompentDataStatistics> data)
        {
            var datetimestring = SelectDateStringByDate(data);
            var model = new PlotModel();
            model.Title = "该时间段的不同状态详细情况";
            //  1.先把所有的开始时间获取到作为X轴
            var xdata = data.GroupBy(d => d.StartTime)
            .Select(g => new { Date = g.Key.ToString(datetimestring) })
            .OrderBy(d => d.Date)
            .ToList().Distinct();

            List<string> xArry = new List<string>();
            foreach (var item in xdata)
            {
                xArry.Add(item.Date);
            }

            var valueAxis1 = new LinearAxis
            {
                Title = "持续时间 单位（分钟）",
                Position = AxisPosition.Left,
                MinimumPadding = 0.06,
                MaximumPadding = 0.06,
                ExtraGridlines = new[] { 0d },
                Key = "y1"
            };


            model.Axes.Add(valueAxis1);
            var series = new List<BarSeries>();
            var (enumValues, enumValueInts, descriptions) = StatusEnumHelper.GetEnumCollections();
            foreach (var item in descriptions)
            {

                var barmodel = new BarSeries() { XAxisKey = "y1", YAxisKey = "x1", Title = item };
                series.Add(barmodel);

            }
            ///循环天数
            foreach (var x in xArry)
            {


                ///huoqu到当天的数据
                var xalldata = data.Where(e => e.StartTime.ToString(datetimestring) == x).ToList();

                ///当天的数据按照Status进行分组
                var mydata = xalldata.GroupBy(d => d.Status).Select(g => new { Status = g.Key, Time = g.Sum(d => d.TotalSecondTime) / 60 });


                //接下来应该对status进行循环有的话为Value 没有的话为0

                foreach (var enumitem in enumValues)
                {
                    var serial = series.Where(e => e.Title == enumitem.GetDescription()).ToList().FirstOrDefault() ?? null;
                    var resultdata = mydata.Where(m => m.Status == enumitem).ToList().FirstOrDefault();


                    if (resultdata == null)
                    {
                        serial.Items.Add(new BarItem() { Value = 0 });
                    }
                    else
                    {
                        serial.Items.Add(new BarItem() { Value = resultdata.Time });
                    }
                }

            }
            var categoryAxis = new CategoryAxis
            {
                Title = "时间",
                ItemsSource = xArry,
                Position = AxisPosition.Bottom,
                Angle = 90,
                Key = "x1"

            };
            //数据添加完事了 接下来添加serial
            model.Axes.Add(categoryAxis);
            foreach (var item in series)
            {
                model.Series.Add(item);
            }

            Legend l = new Legend();
            l = GetLanguage();

            model.Legends.Add(l);
            TubeEveryAlarmByTimeModel = model;

        }


        private string SelectDateStringByDate(List<CompentDataStatistics> data)
        {
            if (data.Count == 0)
            {
                return "yyyy-MM-dd";

            }

            var datelist = data.Select(e => e.StartTime);

           
            var mindate = datelist.Min();

            var maxdate = datelist.Max();

            TimeSpan timeDifference = maxdate - mindate;


            if (timeDifference.TotalDays < 30)
            {
                return "yyyy-MM-dd";
            }
            if (timeDifference.TotalDays > 30 && timeDifference.TotalDays < 365)
            {
                return "yyyy-MM";
            }
            else
            {

                return "yyyy";

            }
        }

        private Legend GetLanguage()
        {
            Legend legend = new Legend()
            {

                LegendBorder = OxyColors.Black,
                LegendBackground = OxyColor.FromAColor(200, OxyColors.White),
                LegendPosition = LegendPosition.LeftTop,
                LegendPlacement = LegendPlacement.Outside,
                LegendOrientation = LegendOrientation.Horizontal,
                LegendItemOrder = LegendItemOrder.Normal,
                LegendItemAlignment = HorizontalAlignment.Left,
                LegendSymbolPlacement = LegendSymbolPlacement.Right,

            };

            return legend;

        }
        /// <summary>
        /// 设备数据折线图
        /// </summary>
        /// <param name="data"></param>
        private void QueryTubeDataLineBarChartModel(List<CompentDataStatistics> data)
        {
            //x轴为各个状态
            //y轴为 各个状态的持续时间
            //图表类型为柱状图 serial 为各个炉管名称
            var model = new PlotModel { Title = "各组件状态占比统计", Subtitle = "" };
            var xArry = new List<string>();
            var (enumValues, enumValueInts, descriptions) = StatusEnumHelper.GetEnumCollections();
            foreach (var item in descriptions)
            {
                xArry.Add(item);
            }
            var categoryAxis = new CategoryAxis
            {
                Title = "各状态",
                ItemsSource = xArry,
                Position = AxisPosition.Bottom,
                Key = "x1"
                ,Angle=70
            };
            var valueAxis1 = new LinearAxis
            {
                Title = "持续时间 单位（分钟）",
                Position = AxisPosition.Left,
                MinimumPadding = 0.06,
                MaximumPadding = 0.06,
                ExtraGridlines = new[] { 0d },
                Key = "y1"
            };
            model.Axes.Add(categoryAxis);
            model.Axes.Add(valueAxis1);
            var series = new List<BarSeries>();
            ///在此修改为
            ///
            var compentlist=this.EventModel.DeviceModel.DeviceComponents.Select(e => e.ComponentName).ToList();
            foreach (var item in compentlist)
            {
                var barmodel = new BarSeries() { XAxisKey = "y1", YAxisKey = "x1", Title = item };
                series.Add(barmodel);//炉管1，2，3
            }

            ///先按按照状态分组  
            var groupeStatusdData = data.GroupBy(d => d.Status).ToList();

            foreach(var item in groupeStatusdData)          
            {
                //再次按照部件code分组并且
                var groupByComponent = item.GroupBy(d => d.ComponentName).Select( g=>new { Code=g.Key, TotalTime = g.Sum(d => d.TotalSecondTime) / 60 }).ToList();

                foreach (var item2 in groupByComponent)
                {
                    var serial = series.Where(e => e.Title == item2.Code).ToList().FirstOrDefault() ?? null;
                    if (serial != null)
                    {
                        serial.Items.Add(new BarItem() { Value = item2.TotalTime });
                    }
                }
            };
            foreach (var item in series)
            {
                model.Series.Add(item);
            }
            Legend l = new Legend();
            l = GetLanguage();
            model.Legends.Add(l);
           
            TubeDataLineBarChartModel = model;
        }
        private void QuaryDeviceDataToDataGid(List<CompentDataStatistics> data)
        {
            QueryDataList = new ObservableCollection<CompentDataStatistics>(data);
        }
      
        private ObservableCollection<CompentDataStatistics> _QueryDataList;
        public ObservableCollection<CompentDataStatistics> QueryDataList
        {
            get { return _QueryDataList; }
            set
            {
                SetProperty(ref _QueryDataList, value);
            }
        }





    }
}
